<% layout('/layout/default.html', {title: '流程表单', libs: ['validate', 'icheck','sheetJs', 'dataGrid']}){ %>
<div class="main-content">
    <div class="container-fluid">
        <form id="inputForm" class="form-horizontal" action="${ctx}/act/flowForm/saveForm" method="post">
            <div class="card-body">
                <input id="businessId" type="hidden" name="businessId" value="${act.businessId}"/>
                <input type="hidden" name="taskId" value="${act.taskId}"/>
                <input type="hidden" name="taskName" value="${act.taskName}"/>
                <input type="hidden" name="taskDefKey" value="${act.taskDefKey}"/>
                <input type="hidden" name="formId" value="${act.formId}"/>
                <input type="hidden" name="modelVersion" value="${act.modelVersion}"/>
                <input type="hidden" id="procInsId" name="procInsId" value="${act.procInsId}"/>
                <input type="hidden" name="procDefId" value="${act.procDefId}"/>
                <input type="hidden" id="flag" name="flag"/>

                <%
                    print(formContent);
                %>

                <input type="hidden" id="fileIds" name="fileIds" />
            </div>
            <% if(act.status != "finish") { %>
                <div class="box-footer">
                    <div class="row">
                        <div class="offset-md-2 col-md-10">
                            <% if(act.status == "edit") { %>
                                <button type="button" class="btn btn-sm btn-primary" onclick="editFlowData();" ><i class="fa fa-check"></i> 保存修改</button>
                                <button type="button" class="btn btn-sm btn-default" onclick="window.parent.closeCurrentTabPage();"><i class="fa fa-reply-all"></i> 关 闭</button>
                            <% } else { %>
                                <% if(isNotEmpty(act.procInsId)) {
                                var isAdjust = (act.taskDefKey=="adjustApply");
                                %>
                                <button type="submit" class="btn btn-sm btn-primary" onclick="$('#flag').val('yes')" ><i class="fa fa-check"></i>${isAdjust?'重新发起':'同  意'} </button>
                                <% if(act.hasUnAuditPassFlow) { %>
                                <button type="submit" class="btn btn-sm btn-danger" onclick="$('#flag').val('no')" ><i class="fa fa-check"></i>${isAdjust?'结束流程':'驳  回'}</button>
                                <% } %>
                                <% } else { %>
                                <button type="submit" class="btn btn-sm btn-primary" onclick="$('#flag').val('yes')" ><i class="fa fa-check"></i> 发起流程</button>
                                <% } %>
                                <button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="window.parent.closeCurrentTabPage();"><i class="fa fa-reply-all"></i> 关 闭</button>
                            <% } %>

                        </div>
                    </div>
                </div>
            <% } %>
        </form>
        <% if(isNotEmpty(act.procInsId)) { %>
            <#form:histoicFlow procInsId="${act.procInsId}" isSubTag="false"/>
        <% } %>
    </div>
</div>
<% } %>
<script>
    var procInsId = $("#procInsId").val();
    procInsId = (procInsId==null || procInsId=="")?"${act.procDefId}".replace(/:/g, ""):procInsId;
    $('#dataGrid').jqGrid({
        url: ('${ctx}/file/sysFile/flowFileData?mainId='+procInsId),//组件创建完成之后请求数据的url
        datatype: "json",//请求数据返回的类型。可选json,xml,txt
        colNames : [ 'ID', '附件名称', '附件大小', '路径', '上传时间', '操作'],//jqGrid的列显示名字。不填写，colModel里面用label也可以
        colModel: [
            //jqGrid每一列的配置信息。包括名字，索引，宽度,对齐方式.....
            { name: 'id', label: 'ID', index: 'id', width: 55, hidden: true,key:true },
            { name: 'name', index: 'a.name', width: 90 },
            { name: 'fileSize', index: 'a.file_size', width: 60, formatter: function(val, obj, row, act){
                    return js.renderSize(val);
                }},
            { name : 'path', index: 'a.path', width : 120},
            { name : 'createDate', index: 'a.create_date', width : 80},
            { name: '操作', index: 'actions', width: 80, align: "center", formatter: function(val, obj, row, act){
                    var actions = [];

                    actions.push('<a href="/file/upload/'+row.path+'" title="下载" download><i class="fa fa-download"></i></a>');
                    var procInsId = $("#procInsId").val();
                    if(procInsId == "" || procInsId == null){
                        actions.push('<a href="javascript:deleteFile(\''+row.id+'\')" title="删除文件"><i class="far fa-trash-alt"></i></a>');
                    }
                    return actions.join('');
                }}
        ],
        jsonReader: { 	// 自定义表格的JSON读取参数
            id: "id", root: "list", page: "pageNo", userdata: "otherData",
            total: "totalPage", records: "count", subgrid: {root:"list"}
        },
        prmNames: {		// 自定义Ajax请求参数
            page:"pageNo", rows:"pageSize", sort: "orderBy",
            order: "sord", search:"_search", nd:"nd", id:"id",
            oper:"oper",editoper:"edit",addoper:"add",deloper:"del",
            subgridid:"id", npage: null, totalrows:"totalPage"
        },
        // rowNum : 10,//一页显示多少条
        // rowList : [ 10, 20, 30 ],//可供用户选择一页显示多少条
        // pager : '#dataGridPage',//表格页脚的占位符(一般是div)的id
        // pginput:false,
        sortname : 'id',//初始化的时候排序的字段
        sortorder : "desc",//排序方式,可选desc,asc
        mtype : "post",//向后台请求数据的ajax的类型。可选post,get
        viewrecords : true,
        gridComplete : function () {
            var gridWidth = 0;
            var jqGridParent = $('#dataGrid').parents('.ui-jqgrid').parent();
            if (jqGridParent.is(':visible')) {
                gridWidth = jqGridParent.width() - 2;
            }
            if (gridWidth != 0) {
                $('#dataGrid').jqGrid('setGridWidth', gridWidth, $(window).width() > 500);
            }
        },
        loadComplete: function(data){
            var procInsId = $("#procInsId").val();
            var ids = "";
            if(procInsId==null || procInsId==""){
                console.log(data);
                for(var i = 0; i < data.length; i++){
                    ids+=data[i].id+",";
                }
            }
            $("#fileIds").val(ids == ""?"":ids.substring(0,ids.length-1));
        }
    });



</script>
<script type="text/javascript">
    $("#inputForm").validate({
        submitHandler: function(form){
            js.layer.confirm("您确认要执行该操作吗？", {icon: 3, title:'提示'}, function(index) {

                // select标签如果有disabled属性,表单提交是必须移除disabled属性,否则后台无法获取请求数据
                $('select').each(function(){
                    var sel = $(this);
                    sel.removeAttr("disabled");
                });
                js.ajaxSubmitForm($(form), function(data){
                    js.showMessage(data.message);
                    if(data.result == 'true'){
                        window.parent.closeCurrentTabPage(window.parent.refreshTab);
                    }

                });

                js.layer.close(index);
            });
        }
    });

    function editFlowData() {
        js.layer.confirm("您确认要修改流程表单数据吗？", {icon: 3, title:'提示'}, function(index) {

            // select标签如果有disabled属性,表单提交是必须移除disabled属性,否则后台无法获取请求数据
            $('select').each(function(){
                var sel = $(this);
                sel.removeAttr("disabled");
            });
            $("#inputForm").attr('action','${ctx}/act/flowForm/updateFormData');
            js.ajaxSubmitForm($("#inputForm"), function(data){
                js.showMessage(data.message);
                $("#inputForm").attr('action','${ctx}/act/flowForm/saveForm');
                if(data.result == 'true'){
                    window.parent.closeCurrentTabPage(window.parent.refreshTab);
                }

            });

            js.layer.close(index);
        });
    };

    $(document).ready(function(){
        $("input[leipiplugins='numcount']").each(function(){
            var countEle = $(this);
            var arr = countEle.attr("orgcountfield").split(",");
            $.each(arr, function (index, val) {
                $("input[name='"+val+"']").focus(function(){
                    $(this).attr("data-oval",$(this).val());
                }).blur(function(){
                    var oldVal=($(this).attr("data-oval"));
                    var newVal=($(this).val());
                    if (oldVal!=newVal) {
                        calculaTotal(countEle);
                    }
                });
            });
        });

        function calculaTotal(countEle) {
            var arr = countEle.attr("orgcountfield").split(",");
            var total = 0;
            $.each(arr, function (index, val) {
                var tmp = Number($("input[name='"+val+"']").val());
                if (!isNaN(tmp)) {
                    total += tmp;
                }
            });
            countEle.val(total);
        };

        startSaveTempForm();

    });

    function startSaveTempForm() {
        var bussinessId = $("#businessId").val();
        if (bussinessId == null || bussinessId == "") {
            setInterval(saveTempForm, 60000);
        }
    }

    function saveTempForm() {
        $("#inputForm").ajaxSubmit({
            type: "POST",
            xhrFields: {
                withCredentials: true
            },
            url: "/jsite/a/act/flowForm/saveFormTemp",
            dataType: "json",
            async: true,
            error: function(data) {
            },
            success: function(data, status, xhr) {
                js.showMessage("自动保存成功");
            }
        });
    }
</script>

<script type="text/javascript">

    function openSelectPersonDialog(assigneeId) {
        js.layer.open({
            type: 2,
            title: '选择下一步处理人',
            shadeClose: true,
            scrollbar: false,
            shade: 0.3,
            area: ['280px', '80%'],
            content: "${ctx}/tag/treeselectNew?url=/sys/office/treeData?type=3", //iframe的url
            btn: ['<i class="fa fa-plus"></i> 确定', '<i class="fa fa-times"></i> 取消'],
            btn1: function(index, layero){
                var win = js.layer.iframeWindow(index);

                var tree = win.tree;//$("#tree");//h.find("iframe").contents();
                var ids = [], names = [], nodes = [];
                nodes = tree.getSelectedNodes();
                for(var i=0; i<nodes.length; i++) {
                    ids.push(nodes[i].loginName);
                    names.push(nodes[i].name);
                    break;
                }


                // $("#nextAssignee").val(ids.join(",").replace(/u_/ig,""));
                $("#"+assigneeId).val(names.join(",") + "," + ids.join(",").replace(/u_/ig,""));

                js.layer.close(index);
            },
            btn2: function(index, layero){

            }
        });
    }

    function openFileUploadDialog() {
        js.layer.open({
            type: 2,
            area: ['65%', '50%'],
            fixed: true, //不固定
            maxmin: true,
            shadeClose: false,
            title:'文件上传',
            content: [('${ctx}/file/sysFile/flowUploadFile?mainId='+procInsId),'auto'],
            cancel: function(index, layero){
                var body = js.layer.getChildFrame('body', index); //得到iframe页的body内容
                var fileIds = body.find("#fileIds").val();

                var exitFile = $("#fileIds").val();
                $("#fileIds").val((exitFile == "" || exitFile == null)?fileIds:(exitFile + "," + fileIds));

                $('#dataGrid').trigger("reloadGrid");
            }
        });
    }


    function deleteFile(id){
        var url = '${ctx}/file/sysFile/delete?';
        js.ajaxRequest(url,{id:id},function(data){
            js.showMessage(data.message);
            if(data.result){
                $("#"+id).remove();
            }
        })
    }

    function openSelectPersonsDialog(assigneeId) {
        js.layer.open({
            type: 2,
            title: '选择下一步处理人',
            shadeClose: true,
            scrollbar: false,
            shade: 0.3,
            area: ['280px', '80%'],
            content: "${ctx}/tag/treeselectNew?url=/sys/office/treeData?type=3&checked=true", //iframe的url
            btn: ['<i class="fa fa-plus"></i> 确定', '<i class="fa fa-times"></i> 取消'],
            btn1: function(index, layero){
                var win = js.layer.iframeWindow(index);

                var tree = win.tree;//$("#tree");//h.find("iframe").contents();
                var nodes = tree.getCheckedNodes();
                var person = [];

                for(var i=0; i<nodes.length; i++) {
                    if (nodes[i].loginName != undefined) {
                        person.push(nodes[i].name + "," + nodes[i].loginName.replace(/u_/ig,""));
                    }
                }

                // $("#nextAssignee").val(ids.join(",").replace(/u_/ig,""));
                $("#"+assigneeId).val(person.join("|"));

                js.layer.close(index);
            },
            btn2: function(index, layero){

            }
        });
    }
</script>